var doNotRedirectBecauseDeleteWasPressed = false;
var furtherElements = true;
function getXMLObject() // XML OBJECT
{
	var xmlHttp = false;
	try {
		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft
		// Browsers
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft
			// IE
			// 6.0+
		} catch (e2) {
			xmlHttp = false // No Browser accepts the XMLHTTP Object then false
		}
	}

	if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
		xmlHttp = new XMLHttpRequest(); // For Mozilla, Opera Browsers
	}
	return xmlHttp; // Mandatory Statement returning the ajax object created
}

var xmlhttp = new getXMLObject(); // xmlhttp holds the ajax object

// -------------------------------------------------
// ------------------SEARCH-------------------------
// -------------------------------------------------
/**
 * this function searches for posts
 * 
 * @param searchStr
 *            the char sequence which has to be in the post
 */

function search(searchStr) {
	deleteAllDiv();
	if (searchStr.length > 1) {
		var getdate = new Date(); // Used to prevent caching during ajax call
		if (xmlhttp) {
			xmlhttp.open("GET", "Search?searchString=" + searchStr, true);
			xmlhttp.onreadystatechange = searchResponse;
			xmlhttp.setRequestHeader('Content-Type',
					'application/x-www-form-urlencoded');
			xmlhttp.send(null);
		}
	}
}

// creates search previews under the search bar
function searchResponse() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var contents = xmlhttp.responseText;
			if (contents.indexOf(" ") != -1)
				createPreviewByList(contents, 0);
		}
	}
}

/**
 * recursive method to add a list of preview items
 * 
 * @param list
 *            a list of preview items separated by the string "<TRENNSYMBOL>"
 * @param at
 *            which pos the output shall start (0 by default)
 */
function createPreviewByList(list, pos) {
	var contentItems = list.split("<TRENNSYMBOL>");
	previewContent = contentItems[pos];
	var index = previewContent.split(" ", 1)[0];
	var content = previewContent.substring(previewContent.indexOf(" "));

	// create a new div
	var newdiv = document.createElement("div");
	document.getElementById("previewField").appendChild(newdiv);

	// set some attributes for the new field
	var divname = 'preview' + new Date().getTime();
	newdiv.setAttribute('id', divname);
	newdiv.setAttribute('stlye', "word-wrap:break-word;");
	newdiv.setAttribute('onmouseup', "redirectToSearchResult(" + index + ")");
	newdiv.className = "round topFloat";

	// inserting the content into the div
	newdiv.innerHTML = content;
	// close link
	pos++;
	if (contentItems.length > pos) {
		createPreviewByList(list, pos);
	}
}

function redirectToSearchResult(index) {
	if(doNotRedirectBecauseDeleteWasPressed == false) {
		var searchstr = document.getElementById("searchInput").value;
		window.location="blog.jsp?id=" + index+"&search="+searchstr;
	}
	doNotRedirectBecauseDeleteWasPressed = false;
}

// helper function to delete a div
function deleteDiv(navigationField, divname) {
	doNotRedirectBecauseDeleteWasPressed = true;
	navigationField.removeChild(divname);
}

// deletes all div from the preview field (this is the area under the search
// bar)
function deleteAllDiv() {
	var nodes = document.getElementById("previewField").childNodes;
	for (i = 0; i < nodes.length; i++) {
		if (nodes[i].id != null) {
			if (nodes[i].id.indexOf("preview") != -1) {
				document.getElementById("previewField").removeChild(nodes[i]);
				i--;
			}
		}
	}
}

// -------------------------------------------------
// -------------------POST--------------------------
// -------------------------------------------------

// ------------------DELETE-------------------------
/**
 * AJAX function to delete a post
 */
function deletePost(id) {
	var getdate = new Date(); // Used to prevent caching during ajax call
	if (xmlhttp) {
		var parameters = "type=delete&id=" + id;
		xmlhttp.open("POST", "post", true);
		xmlhttp.onreadystatechange = deletePostResponse;
		xmlhttp.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded');
		xmlhttp.send(parameters);
	}
}

function deletePostResponse() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var post = xmlhttp.responseText + "";
			var el = document.getElementById("post" + post);
			document.getElementById("postsList").removeChild(el);
		}
	}
}

//------------------EDIT-------------------------
function editPost() {
	if(params.id==null)
		return;
	
	var form = document.createElement("form");
	form.setAttribute("action", "/post");
	form.setAttribute("method", "post");
	
	var hiddenId = document.createElement("input");
	hiddenId.setAttribute("type", "hidden");
	hiddenId.setAttribute("name", "id");
	hiddenId.setAttribute("value", params.id);
	form.appendChild(hiddenId);
	
	var hiddenEditFlag = document.createElement("input");
	hiddenEditFlag.setAttribute("type", "hidden");
	hiddenEditFlag.setAttribute("name", "type");
	hiddenEditFlag.setAttribute("value", "edit");
	form.appendChild(hiddenEditFlag);

	var outerDiv = document.createElement("div");
	form.appendChild(outerDiv);

	var titleDiv = document.createElement("div");
	titleDiv.setAttribute("class", "small textarea round");
	outerDiv.appendChild(titleDiv);

	var titleInput = document.createElement("input");
	titleInput.setAttribute("class", "fullwidth textarea");
	titleInput.setAttribute("name", "topic");
	titleInput.setAttribute("type", "text");
	titleInput.setAttribute("value", document.getElementById("topic").innerHTML);
	titleDiv.appendChild(titleInput);

	var bodyDiv = document.createElement("div");
	bodyDiv.setAttribute("class", "textarea round");
	form.appendChild(bodyDiv);

	var ta = document.createElement("textarea");
	ta.setAttribute("class", "small round textarea fullwidth");
	ta.setAttribute("name", "content");
	ta.setAttribute("rows", "25");
	ta.innerHTML = document.getElementById("postContent").innerHTML;
	bodyDiv.appendChild(ta);

	var submitDiv = document.createElement("div");
	submitDiv.setAttribute("class", "center");
	form.appendChild(submitDiv);

	var submitInput = document.createElement("input");
	submitInput.setAttribute("class", "small round button");
	submitInput.setAttribute("type", "submit");
	submitInput.setAttribute("value", "Change post");
	submitDiv.appendChild(submitInput);

	// clear content
	var el = document.getElementById("postContent");
	document.getElementById("postDiv").removeChild(el);
//	document.getElementById("postContent").innerText = "";
	// delete edit button
	var el = document.getElementById("editButton");
	document.getElementById("postDiv").removeChild(el);
	// delete topic
	el = document.getElementById("topic");
	document.getElementById("postDiv").removeChild(el);
	// delete topic
	el = document.getElementById("plusonediv");
	document.getElementById("postDiv").removeChild(el);

	// add new form
	var bq = document.getElementById("postDiv");
	bq.appendChild(form);
	initializeTinyMCE();
}

// -------------------------------------------------
// -----------------Comments------------------------
// -------------------------------------------------

// ------------------CREATE-------------------------
/**
 * AJAX function to create a new comment
 */
function newComment() {
	var getdate = new Date(); // Used to prevent caching during ajax call
	// send AJAX request
	if (xmlhttp) {
		var parameters = "blogIdInt="
				+ document.getElementById("blogIdInt").value + "&content="
				+ tinyMCE.get('commentField').getContent();
		tinyMCE.get('commentField').setContent("");
		xmlhttp.open("POST", "comment", true);
		xmlhttp.onreadystatechange = addCommentResponseR;
		xmlhttp.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
		xmlhttp.send(parameters);
	}
}

/**
 * adds a Comment in front of the comment list
 */
function addCommentResponseR() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var response = xmlhttp.responseText + "";
			document.getElementById("commentsList").innerHTML = response
					+ document.getElementById("commentsList").innerHTML;
			increaseCommentAmount();
		}
	}
}

/**
 * updates the string how much comments belong to this post
 */
function increaseCommentAmount() {
	if (document.getElementById("commentAmountString").innerHTML == " ") {
		document.getElementById("commentAmountString").innerHTML = "There is one comment:";
	} else if (!document.getElementById("commentAmount")) {
		document.getElementById("commentAmountString").innerHTML = "There are <span id=\"commentAmount\">2</span> comments:"
	} else {
		document.getElementById("commentAmountString").innerHTML = "There are <span id=\"commentAmount\">"
				+ (parseInt(document.getElementById("commentAmount").innerHTML) + 1)
				+ "</span> comments:"
	}
}

// ------------------DELETE-------------------------
/**
 * deletes a comment in the database
 * 
 * @param id
 *            the id of the comment to delete
 */
function deleteComment(id) {
	var getdate = new Date(); // Used to prevent caching during ajax call
	if (xmlhttp) {
		var parameters = "type=delete&id=" + id;
		xmlhttp.open("POST", "comment", true);
		xmlhttp.onreadystatechange = deleteCommentResponse;
		xmlhttp.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded');
		xmlhttp.send(parameters);
	}
}
/**
 * if a comment was deleted successfully the comment will be removed from the
 * page
 */
function deleteCommentResponse() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var id = xmlhttp.responseText + "";
			var el = document.getElementById("comment" + id);
			document.getElementById("commentsList").removeChild(el);
			if (!document.getElementById("commentAmount")) {
				document.getElementById("commentAmountString").innerHTML = " ";
			} else if (document.getElementById("commentAmount").innerHTML == "2") {
				document.getElementById("commentAmountString").innerHTML = "There is one comment:";
			} else {
				document.getElementById("commentAmountString").innerHTML = "There are <span id=\"commentAmount\">"
						+ (parseInt(document.getElementById("commentAmount").innerHTML) - 1)
						+ "</span> comments:"
			}
		}
	}
}

// -------------------------------------------------
// -------------Infinite scroll---------------------
// -------------------------------------------------

/**
 * scroll() is called every second if the user is nearly at the bottom of the
 * site, new comments will be loaded
 */
function scroll(){  
		//if((document.documentElement.clientHeight - window.pageYOffset) < 1000){  
	if(furtherElements == true) {
		if ((document.documentElement.scrollHeight) - 100 < (parseInt(document.body.scrollTop)+parseInt(window.innerHeight))){
			var element;
			var type;
			if(document.getElementById("commentsList")) {
				element = document.getElementById("commentsList");
				type = "comment";
			} else if(document.getElementById("postsList")) {
				element = document.getElementById("postsList");
				type = "post";
			} else {
				return;
			}
	    	amount = element.getElementsByTagName("div").length;
	    	if (xmlhttp) {
	    		var parameters = "type=reload&offset="+amount;
	    		xmlhttp.open("POST", type, true);
	    		if (type == "comment") {
	    			parameters += "&id="+getParameterByName("id");
	    			xmlhttp.onreadystatechange = addCommentResponse;
	    		}
	    		if (type == "post") {
	    			parameters += "&user="+getParameterByName("filter");
	    			xmlhttp.onreadystatechange = addPostResponse;
	    		}
	    		xmlhttp.setRequestHeader('Content-Type',
	    				'application/x-www-form-urlencoded');
	    		xmlhttp.send(parameters);
	    	}
	    }
	}
}  

/**
 * fetches an attribute from the URL
 */
function getParameterByName(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.search);
	if (results == null)
		return "";
	else
		return decodeURIComponent(results[1].replace(/\+/g, " "));
}

/**
 * adds Comments to the end of the comment list, does not change the amount of
 * comments
 */

function addCommentResponse() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			if (xmlhttp.responseText=="\n")
				furtherElements = false;
			var response = xmlhttp.responseText + "";
			document.getElementById("commentsList").innerHTML += response;
		}
	}
}

/**
 * adds posts to the posts list
 */
function addPostResponse() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			if (xmlhttp.responseText=="\n")
				furtherElements = false;
			var response = xmlhttp.responseText + "";
			document.getElementById("postsList").innerHTML+=response;
		}
	}
}
//-------------------------------------------------
//------------------- Admin -----------------------
//-------------------------------------------------

/**
 * @brief Send request to create a new admin from input fields
 */
function newAdmin() {
	// send AJAX request
	if (xmlhttp) {
		var parameters = "type=newAdmin&username="
				+ document.getElementById("username").value + "&canPost="
				+ document.getElementById("canPost").checked + "&isAdmin="
				+ document.getElementById("isAdmin").checked;
		xmlhttp.open("POST", "admin", true);
		xmlhttp.onreadystatechange = function() {
			document.getElementById('username').value = "";
			if (this.readyState != 4)
				return;
			if (this.status == 200) {
				if (xmlhttp.responseText == "")
					return;
				var table = document.getElementById("adminList");
				if (table == null)
					return;
				var rowCount = table.rows.length;
				var row = table.insertRow(rowCount - 1);
				row.innerHTML = xmlhttp.responseText;
			}
		};
		xmlhttp.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
		xmlhttp.send(parameters);
	}
}

/**
 * @brief Modify the user that is given by the html tag
 * @param aTag
 */
function modifyAdmin(aTag) {
	var getdate = new Date(); // Used to prevent caching during ajax call
	if (xmlhttp) {
		try {
			var row = aTag.parentElement.parentElement;
		} catch (err) {
			console.log("Could not get row from aTag: " + err);
			return;
		}
		try {
			var tds = row.getElementsByTagName("td");
			var username = tds[0].innerText;
			var canPost = tds[1].getElementsByTagName("input")[0].checked ? 1
					: 0;
			var isAdmin = tds[2].getElementsByTagName("input")[0].checked ? 1
					: 0;
			if (username == null || canPost == null || isAdmin == null)
				throw new Exception("username is null");
		} catch (err) {
			console.log("Could not extract username: " + err);
			return;
		}

		var parameters = "type=modifyAdmin&username=" + username + "&canPost="
				+ canPost + "&isAdmin=" + isAdmin;

		xmlhttp.open("POST", "admin", true);
		xmlhttp.row = row;
		xmlhttp.onreadystatechange = function() {
			if (this.readyState != 4)
				return;
			if (this.status == 200) {
				// hm... do anything?
			}
		}
		xmlhttp.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded');
		xmlhttp.send(parameters);
	}
}

/**
 * @brief delete the user that is given by the html tag
 * @param aTag
 */
function deleteAdmin(aTag) {
	var getdate = new Date(); // Used to prevent caching during ajax call
	if (xmlhttp) {
		try {
			var row = aTag.parentElement.parentElement;
		} catch (err) {
			console.log("Could not get row from aTag: " + err);
			return;
		}
		try {
			var username = row.getElementsByTagName("td")[0].innerText;
			if (username == null)
				throw new Exception("username is null");
		} catch (err) {
			console.log("Could not extract username: " + err);
			return;
		}

		var parameters = "type=deleteAdmin&username=" + username;
		xmlhttp.open("POST", "admin", true);
		xmlhttp.row = row;
		xmlhttp.onreadystatechange = function() {
			if (this.readyState != 4)
				return;
			if (this.status == 200) {
				// delete
				try {
					var table = this.row.parentElement;
					table.removeChild(this.row);
				} catch (err) {
					console.log("There was an Exception: " + err);
				}
			}
		}
		xmlhttp.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded');
		xmlhttp.send(parameters);
	}
}

/**
 * Initialize text editor (tinyMCE: http://www.tinymce.com/)
 */
function initializeTinyMCE() {
	tinyMCE
			.init({
				// General options
				mode : "textareas",
				theme : "advanced",
				// height : "100",
				plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

				// Theme options
				theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,link,image",
				theme_advanced_buttons2 : "",
				// theme_advanced_buttons1 :
				// "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
				// theme_advanced_buttons2 :
				// "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
				// theme_advanced_buttons3 :
				// "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
				// theme_advanced_buttons4
				// :"insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
				// theme_advanced_toolbar_location : "top",
				// theme_advanced_toolbar_align : "left",
				// theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,
				width : '100%',

				// Skin options
				skin : "o2k7mod",
				// skin_variant : "black",

				// Example content CSS (should be your site CSS)
				content_css : "stylesheets/bg.css",

				// Drop lists for link/image/media/template dialogs
				template_external_list_url : "js/template_list.js",
				external_link_list_url : "js/link_list.js",
				external_image_list_url : "js/image_list.js",
				media_external_list_url : "js/media_list.js",

			// Replace values for the template plugin
			// template_replace_values : {
			// username : "Some User",
			// staffid : "991234"
			// }
			});
	(function() {
		var po = document.createElement('script');
		po.type = 'text/javascript';
		po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(po, s);
	})();
}

// initialize any textarea to a tinyMCE
initializeTinyMCE();

var prmstr = window.location.search.substr(1);
var prmarr = prmstr.split ("&");
var params = {};

for ( var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
}
